package JUC.AQS.DebugDemo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

import JUC.AQS.concurrent.ReentrantLock;


/**
 * @author CKC
 * @DateTime 2021/7/17 18:04
 */
public class DebugAQSDemo {
    
    private static ReentrantLock lock = new ReentrantLock(true);
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();
    
    public static void main(String[] args) {
//        new Thread(DebugAQSDemo::demo1, "t0").start();
//        new Thread(DebugAQSDemo::demo1, "t1").start();
        new Thread(DebugAQSDemo::demo2, "t2").start();
//        new Thread(DebugAQSDemo::demo2, "t3").start();
//        new Thread(DebugAQSDemo::demo3, "t4").start();
//        new Thread(()->{
//            try {
//                DebugAQSDemo.demo4();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        },"t5").start();
        try {
            Thread.sleep(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void demo1() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "===");
        } finally {
            lock.unlock();
        }
    }
    
    public static void demo2() {
        lock.lock();
        try {
//            LockSupport.unpark(Thread.currentThread());
            System.out.println(Thread.currentThread().getName() + "===");
            condition1.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
    public static void demo3() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "===");
            condition1.signalAll();
        } finally {
            lock.unlock();
        }
    }
    
    public static void demo4() throws InterruptedException {
        if (lock.tryLock(3, TimeUnit.MINUTES)) {
            boolean await = condition1.await(300L, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName() + "=====demo4");
            lock.unlock();
        }
    }
}
